<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta charset="utf-8" />
    <title>Web推送</title>
    <style>
        body{
            text-align: center;
            padding: 50px;
        }
        #txtConfig{
            width: 80%;
            margin-top: 30px;
        }
    </style>
  </head>
  <body>
    <button id="btnConfig">获取通知配置</button>
    <br />
    <textarea  id="txtConfig" rows="20"></textarea>
    <script>
function registerPush(appPubkey) {
    navigator.serviceWorker.register('sw.js?v=2');
    navigator.serviceWorker.ready.then(function(registration) {
        return registration.pushManager.getSubscription()
            .then(function(subscription) {
                if (subscription) {
                    return subscription;
                }

                return registration.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey: urlBase64ToUint8Array(appPubkey)
                });
            }) 
            .then(function(subscription) {
                document.getElementById('txtConfig').textContent = JSON.stringify(subscription, null, "\t")
            });
    });
}

function urlBase64ToUint8Array(base64String) {
    var padding = '='.repeat((4 - base64String.length % 4) % 4);
    var base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');

    var rawData = window.atob(base64);
    var outputArray = new Uint8Array(rawData.length);

    for (var i = 0; i < rawData.length; ++i)  {
        outputArray[i] = rawData.charCodeAt(i);
    }

    return outputArray;
}

document.getElementById('btnConfig').onclick = function(){
    if (navigator.serviceWorker) {
        registerPush('BIY9wd7fR1h5Mn1UguOEiytD_nq91PWvxDW12cApNvZdHWZoEAqk5OyuPeNnGE0MlegLO5cVMvxqIPzQHijCDQE');
    }else{
        alert("当前浏览器不支持此功能！")
    }
}
    </script>
  </body>
</html>